package com.lalilu.homework9;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

import java.io.IOException;

public class MusicHelper {
    private MediaPlayer mediaPlayer;
    private final Context context;
    private final int[] musicList = new int[]{R.raw.cy8er};
    private int musicIndex = 0;
    private boolean prepared = false;

    public MusicHelper(Context context) {
        this.context = context;
        createMediaPlayer();
    }

    public void createMediaPlayer() {
        this.mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    public void play() {
        if (mediaPlayer == null) createMediaPlayer();
        if (mediaPlayer.isPlaying()) return;
        if (prepared) {
            mediaPlayer.start();
            return;
        }

        try {
            mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.lalilu.homework9/" + musicList[musicIndex]));
        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(mp -> {
            mp.start();
            prepared = true;
        });
    }

    public void pause() {
        if (mediaPlayer.isPlaying()) pause();
    }

    public void next() {
        musicIndex++;
        musicIndex = musicIndex % musicList.length;
        destroy();
        createMediaPlayer();
        play();
    }

    public void destroy() {
        if (mediaPlayer == null) return;

        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
        prepared = false;
    }
}
